
package controllers;

import entity.Users;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Timer;
import javax.ejb.EJB;
import javax.ejb.Timeout;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import services.implementation.ForHelp;
import services.implementation.RegistrationService;
import services.implementation.SendMail;
import services.implementation.UsersService;

/*
 * @author smile
 */

@ManagedBean
@RequestScoped
public class UserManagerController {
    @EJB
    private RegistrationService registrationService;
    @EJB
    private UsersService usersService;

    private String _login;
    private String _password;
    private String _repassword;
    private String _newPassword;
    private String _reNewPassword;
    private String _email;
    private String _newEmail;
    private String _reNewEmail;
    
    public String getNewPassword() {
        return _newPassword;
    }

    public void setNewPassword(String _newPassword) {
        this._newPassword = _newPassword;
    }

    public String getReNewPassword() {
        return _reNewPassword;
    }

    public void setReNewPassword(String _reNewPassword) {
        this._reNewPassword = _reNewPassword;
    }
    
    public String getNewEmail() {
        return _newEmail;
    }

    public void setNewEmail(String _newEmail) {
        this._newEmail = _newEmail;
    }

    public String getReNewEmail() {
        return _reNewEmail;
    }

    public void setReNewEmail(String _reNewEmail) {
        this._reNewEmail = _reNewEmail;
    }
    
    public String getEmail() {
        return _email;
    }

    public void setEmail(String _email) {
        this._email = _email;
    }

    public String getLogin() {
        return _login;
    }

    public void setLogin(String _login) {
        this._login = _login;
    }

    public String getPassword() {
        return _password;
    }

    public void setPassword(String _password) {
        this._password = _password;
    }

    public String getRepassword() {
        return _repassword;
    }

    public void setRepassword(String _repassword) {
        this._repassword = _repassword;
    }
    
    /*
     * Creates a new instance of UserManagerController 
     */
    public UserManagerController() {
    }
    
    /*
     * User registration.
     */
    public String createUser() {
        
        // if email does not exist then continue
        if (usersService.findByEmail(this._email).isEmpty()) {
            if (!this._password.equals(this._repassword)) {
                ForHelp.addErrorMessage(ResourceBundle
                    .getBundle("/Bundle")
                    .getString("Authentication.Password.DoNotMatch"));
                return null;
            }
            try {
                registrationService.registration(
                        this._email, 
                        this._login, 
                        this._password,
                        "USER");
                return "/index";
            }catch (Exception e){
                ForHelp.addErrorMessage(ResourceBundle
                    .getBundle("/Bundle")
                    .getString("Authentication.Creating.Error"));
                return null;
            }
        }else{ // This e-mail already exists
            ForHelp.addErrorMessage(ResourceBundle
                        .getBundle("/Bundle")
                        .getString("Authentication.Email.Exist"));
            return null;
        }
    }
    
    public String logout() {
            String result="/index?faces-redirect=true";

            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();

            try {
                request.logout();
            } catch (Exception e) {
                ForHelp.addErrorMessage(
                    ResourceBundle
                    .getBundle("/Bundle")
                    .getString("Logout.Error"));
            }

            return result;
    }
    
    public Integer isAuthenticated (){
        FacesContext context = FacesContext.getCurrentInstance();
        if (context.getExternalContext().getUserPrincipal() == null){
            return 0;
        }
        return 1;
    }
    
    public String getAuthenticatedUserName(){
        FacesContext context = FacesContext.getCurrentInstance(); 
        return usersService.findByEmail(context.getExternalContext().getUserPrincipal().getName().toString()).get(0).getLogin().toString();
    }
    
    
    public Integer isRoleAdmin (){
        FacesContext context = FacesContext.getCurrentInstance();
        if (context.getExternalContext().isUserInRole("ADMIN")){
            return 1;
        }
        return 0;
    }

    public String recoveryPassword() throws MessagingException{
        try {
            List<Users> user = usersService.findByEmail(this._email);
            if (user.isEmpty()) {
                ForHelp.addErrorMessage(ResourceBundle
                    .getBundle("/Bundle")
                    .getString("Service.RecoveryPass.DoesNotExist"));
                return null;
            }else {
                String message = "Your old password: " + user.get(0).getPassword();
                String subject = "Password recovery";
                String fromAddress = "ShortNotes";
                SendMail mailClient = new SendMail();
   
                mailClient.postMail(new String[]{user.get(0).getEmail().toString()}, subject, 
                        "Hi " + user.get(0).getLogin() + ", \n" + message, fromAddress);
                return "/index";
            }
        } catch (MessagingException e) {
                ForHelp.addErrorMessage(
                    ResourceBundle
                    .getBundle("/Bundle")
                    .getString("RecoveryPass.Error"));
                return null;
        }
    }
 
    public String changeEmail() throws ServletException {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
        List<Users> user = 
                usersService.findByEmail(context
                    .getExternalContext()
                    .getUserPrincipal()
                    .getName()
                    .toString());
        
        if (user.get(0).getEmail().equals(this._email)){
            if (this._newEmail.equals(this._reNewEmail)){
                if (usersService.updateEmail(user.get(0).getId(), this._newEmail)){
                    request.logout();
                    return "/index";
                } else {
                    ForHelp.addErrorMessage(
                        ResourceBundle
                        .getBundle("/Bundle")
                        .getString("Service.Email.Change.Error"));
                    return "null";
                }
            } else {
                ForHelp.addErrorMessage(
                    ResourceBundle
                    .getBundle("/Bundle")
                    .getString("RecoveryPass.Email.DoNotMatch"));
                return null;
            }
        }else {
            ForHelp.addErrorMessage(
                ResourceBundle
                .getBundle("/Bundle")
                .getString("RecoveryPass.Email.Wrong"));
            return null;
        }
    }
    
    public String changePassword() throws ServletException {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest();
        List<Users> user = 
                usersService.findByEmail(context
                    .getExternalContext()
                    .getUserPrincipal()
                    .getName()
                    .toString());
        
        if (user.get(0).getPassword().equals(this._password)){
            if (this._newPassword.equals(this._reNewPassword)){
                if(usersService.updatePassword(user.get(0).getId(), this._newPassword)){
                    request.logout();
                    return "/index";
                } else {
                    ForHelp.addErrorMessage(
                        ResourceBundle
                        .getBundle("/Bundle")
                        .getString("Service.Password.Change.Error"));
                    return "null";
                }
            } else {
                ForHelp.addErrorMessage(
                    ResourceBundle
                    .getBundle("/Bundle")
                    .getString("RecoveryPass.Password.DoNotMatch"));
                return null;
            }
        }else {
            ForHelp.addErrorMessage(
                ResourceBundle
                .getBundle("/Bundle")
                .getString("RecoveryPass.Password.Wrong"));
            return null;
        }
    }
}
